import json
from django.http import HttpResponse
import muggle_ocr

"""
使用预置模型，预置模型包含了[ModelType.OCR, ModelType.Captcha] 两种
其中 ModelType.OCR 用于识别普通印刷文本, ModelType.Captcha 用于识别4-6位简单英数验证码
"""


def get_text_from_img(captcha_bytes):
    # ModelType.eb
    # Captcha 可识别4-6位验证码
    sdk = muggle_ocr.SDK(model_type=muggle_ocr.ModelType.Captcha)
    # 3. 调用预测函数
    text = sdk.predict(image_bytes=captcha_bytes)
    print(text)
    return text


"""
view层
"""


def captcha(request):
    # 获取图片文件
    file = request.FILES['image']
    # 打开验证码图片
    captcha_bytes = file.read()
    text = get_text_from_img(captcha_bytes)
    # 返回四个字符才视为正确
    if text.__len__() == 4:
        res_code = 200
    else:
        res_code = 201
    res = {'result': res_code, "msg": text}
    # 返回响应
    res_json = json.dumps(res, ensure_ascii=False)
    return HttpResponse(res_json)